/*
 * Copyright (c) 2023 Huawei Technologies Co., Ltd.
 * openUBMC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *         http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

#include "interface/network_port.h"

namespace dev {

std::string mac_addr_to_hex_string(const uint8_t* mac_addr, size_t len) {
    std::stringstream ss;
    for (size_t i = 0; i < len; ++i) {
        if (i > 0) {
            ss << ":";
        }
        ss << std::hex << std::uppercase << std::setfill('0') << std::setw(2)
           << static_cast<unsigned>(mac_addr[i]);
    }
    return ss.str();
}

bool NetworkPort::update_mac_addr_by_ncsi() {
    if (!m_ncsi_over_mctp_mellanox) {
        elog("Error: NCSI over MCTP not initialized when updating MAC address");
        return false;
    }

    uint8_t mac_addr[6] = {};
    ilog("update MAC address port ${PortId}", ("PortId", PortId));
    bool    ret = m_ncsi_over_mctp_mellanox->get_mac_addr(m_package_id, PortId, mac_addr, 6);
    if (!ret) {
        ilog("Error: Failed to update MAC address");
        return false;
    }
    std::string mac_addr_str = mac_addr_to_hex_string(mac_addr, 6);
    MACAddress.set_value(mac_addr_str);
    return true;
}

bool NetworkPort::update_default_mac_addr_by_ncsi() {
    if (!m_ncsi_over_mctp_mellanox) {
        elog("Error: NCSI over MCTP not initialized when updating default MAC address");
        return false;
    }

    uint8_t mac_addr[6] = {};
    bool    ret =
        m_ncsi_over_mctp_mellanox->get_default_mac_addr(m_package_id, PortId, mac_addr, 6);
    if (!ret) {
        ilog("Error: Failed to update default MAC address");
        return false;
    }
    std::string mac_addr_str = mac_addr_to_hex_string(mac_addr, 6);
    PermanentMACAddress.set_value(mac_addr_str);
    if ((MACAddress == "00:00:00:00:00:00") || (MACAddress == "N/A")) {
        MACAddress.set_value(mac_addr_str);
        ilog("update mac addr: ${mac_addr}", ("mac_addr", mac_addr_str));
    }
    return true;
}

bool NetworkPort::set_lldp_capability_by_ncsi(uint8_t lldp_capability) {
    if (!m_ncsi_over_mctp_mellanox) {
        elog("Error: NCSI over MCTP not initialized when setting LLDP capability");
        return false;
    }

    bool ret = m_ncsi_over_mctp_mellanox->set_lldp_capability(m_package_id, PortId, lldp_capability);
    if (!ret) {
        ilog("Error: Failed to set LLDP capability");
        return false;
    }
    return true;
}

bool NetworkPort::get_lldp_capability_by_ncsi() {
    if (!m_ncsi_over_mctp_mellanox) {
        elog("Error: NCSI over MCTP not initialized when getting LLDP capability");
        return false;
    }

    uint8_t lldp_capability = 0;
    bool ret =
        m_ncsi_over_mctp_mellanox->get_lldp_capability(m_package_id, PortId, &lldp_capability);
    if (!ret) {
        ilog("Error: Failed to get LLDP capability");
        return false;
    }

    if (lldp_capability == 0) {
        LLDPEnabled.set_value(false);
        return true;
    }

    LLDPEnabled.set_value(true);
    return true;
}

void NetworkPort::start_ncsi_update_task_mellanox(ncsi_over_mctp_mellanox_ptr ncsi_over_mctp,
                                                mc::milliseconds      interval,
                                                uint8_t package_id) {
    m_ncsi_over_mctp_mellanox = ncsi_over_mctp;
    m_ncsi_timer            = new mc::core::timer(this);
    m_package_id = package_id;
    
    // 重置计数器
    m_ncsi_timer_counter = 0;
    
    m_ncsi_timer->timeout.connect([this]() {
        // 增加计数器
        m_ncsi_timer_counter++;
        
        // 每10秒执行的任务（每次都执行）
        update_mac_addr_by_ncsi();
        
        // 每120秒执行的任务（每12次执行一次，即120秒/10秒=12）
        if (m_ncsi_timer_counter % 12 == 1) {  // 第1、13、25...次执行
            update_default_mac_addr_by_ncsi();
            get_lldp_capability_by_ncsi();
            dlog("NetworkPort: executed 120s cycle tasks (count=${count})", ("count", m_ncsi_timer_counter));
        }
        
        dlog("NetworkPort: executed 10s cycle tasks (count=${count})", ("count", m_ncsi_timer_counter));
        
        // 防止计数器溢出，每120次重置（即1200秒后重置）
        if (m_ncsi_timer_counter >= 120) {
            m_ncsi_timer_counter = 0;
        }
    });
    
    m_ncsi_timer->set_single_shot(false);
    // 使用10秒作为基础间隔
    m_ncsi_timer->start(mc::milliseconds(10000));
}

void NetworkPort::stop_ncsi_update_task() {
    if (m_ncsi_timer) {
        m_ncsi_timer->stop();
        // delete m_ncsi_timer;
        // m_ncsi_timer = nullptr;
    }
    if (m_ncsi_over_mctp_mellanox) {
        m_ncsi_over_mctp_mellanox = nullptr;
    }
}

bool NetworkPort::SendNcsiTestPacket(uint8_t cmd_code, const std::string& req_data) {
    // 检查NCSI连接是否可用
    if (!m_ncsi_over_mctp_mellanox) {
        ilog("Error: NCSI over MCTP not initialized");
        return false;
    }

    try {
        // 发送NCSI测试包
        bool ret = m_ncsi_over_mctp_mellanox->send_test_packet(m_package_id, PortId, cmd_code,
                                                             req_data);
        if (!ret) {
            ilog("Error: Failed to send NCSI test packet");
            return false;
        }

        return true;
    } catch (const std::exception& e) {
        ilog("Error sending NCSI test packet: ${error}", ("error", e.what()));
        return false;
    }
}

bool NetworkPort::SetLLDPTxEnable(bool enable) {
    // 检查NCSI连接是否可用
    if (!m_ncsi_over_mctp_mellanox) {
        ilog("Error: NCSI over MCTP not initialized");
        return false;
    }

    // 通过设置LLDP capability来启用/禁用LLDP TX
    uint8_t lldp_capability = enable ? ENABLE_LLDP : DISABLE_LLDP;
    bool ret = set_lldp_capability_by_ncsi(lldp_capability);
    if (!ret) {
        ilog("Error: Failed to set LLDP TX enable to ${enable}", ("enable", enable));
        return false;
    }

    // 更新LLDPEnabled属性
    LLDPEnabled.set_value(enable);
    return true;
}

} // namespace dev

MC_REFLECT(dev::NetworkPort)